package com.rou.im.framework.boot.starter.builder;

import com.rou.im.framework.boot.starter.Builder;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2020-05-05 16:22
 */
public abstract class AbstractBuilder<O> implements Builder<O> {
    private AtomicBoolean building = new AtomicBoolean();

    private O object;

    @Override
    public final O build() throws Exception {
        if (this.building.compareAndSet(false, true)) {
            this.object = doBuild();
            return this.object;
        }
        throw new RuntimeException("This object has already been built");
    }


    public final O getObject() {
        if (!this.building.get()) {
            throw new IllegalStateException("This object has not been built");
        }
        return this.object;
    }


    protected abstract O doBuild() throws Exception;
}
